package map.android.baidu.carpool.page.home;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.baidu.components.api.extra.APIProxy;
import com.baidu.lbs.net.http.model.ComNetData;
import com.baidu.lbs.net.http.model.IDataStatusChangedListener;

import android.widget.Toast;
import com.baidu.mapframework.api.ComAPIManager;
import map.android.baidu.carpool.R;
import map.android.baidu.carpool.data.impl.OrderCancelData;
import map.android.baidu.carpool.data.impl.OrderDetailData;
import map.android.baidu.carpool.page.CarpoolBasePage;
import map.android.baidu.carpool.page.usercenter.OrderListPage;
import map.android.baidu.carpool.response.OrderCancelResponse;
import map.android.baidu.carpool.response.OrderDetailResponse;
import map.android.baidu.carpool.utils.CarPoolReceiptDialog;
import map.android.baidu.carpool.utils.HelpUtils;
import map.android.baidu.carpool.utils.TitleHelpler;
import map.android.baidu.carpool.utils.ToastForCarpool;

import java.util.ArrayList;

/**
 * Created by zhaoyangyang on 2015/3/30.
 */
public class CancelOrderPage extends CarpoolBasePage implements View.OnClickListener {
    private View mView = null;
    private ArrayList<String> mReaseonList = null;
    private ArrayList<Integer> mChooseReason = null;

    private ListView mListView = null;
    private ReasonAdapter mReasonAdapter = null;
    private TitleHelpler mTitleHelper;
    private Button mCancelOrderBtn = null;
    private Button mSaveOrderBtn = null;
    private String oderId = "";
    private EditText mInputEditText = null;
    private int mOrderStatus = -100;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            oderId = getArguments().getString("orderId");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mView = APIProxy.res().inflate(R.layout.layout_cancel_page);
        initView();
        initData();
        ComAPIManager.getComAPIManager().
                getResourceAPI(getComId()).getBaseActivity().getWindow().
                setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        return mView;
    }

    private void initView() {
        mTitleHelper = new TitleHelpler(mView);
        mTitleHelper.setLeftView(this);
        mTitleHelper.setCenterViewText("取消订单");
        mReaseonList = new ArrayList<String>();
        mChooseReason = new ArrayList<Integer>();
        mListView = (ListView) mView.findViewById(R.id.reason_list);
        mReasonAdapter = new ReasonAdapter();
        mListView.setAdapter(mReasonAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HelpUtils.closeSoftKeyboard(mInputEditText);
                mChooseReason.clear();
                mChooseReason.add(i);
                if (i == mReaseonList.size() - 1) {
                    mInputEditText.setVisibility(View.VISIBLE);
                } else {
                    mInputEditText.setVisibility(View.GONE);
                }

                mReasonAdapter.notifyDataSetChanged();

            }
        });

        mCancelOrderBtn = (Button) mView.findViewById(R.id.btn_cancel_order);
        mSaveOrderBtn = (Button) mView.findViewById(R.id.btn_save_order);
        mCancelOrderBtn.setOnClickListener(this);
        mSaveOrderBtn.setOnClickListener(this);
        mInputEditText = (EditText) mView.findViewById(R.id.input_reason);
        mInputEditText.setVisibility(View.GONE);
    }

    private void initData() {

        mReaseonList.add("车主无法接单");
        mReaseonList.add("无法按计划出发");
        mReaseonList.add("用车请求发错了");
        mReaseonList.add("其他");
        if (mReaseonList.size() > 0) {
            mChooseReason.add(0);
        }
        mReasonAdapter.notifyDataSetChanged();

    }

    private void cancelOrder() {
        if (!checkNetworkStatus(true)) {
            return;
        }
        OrderCancelData orderCancelData = new OrderCancelData(mActivity);
        orderCancelData.setOrderNo(oderId);
        orderCancelData.setCancelReason(mReaseonList.get(mChooseReason.get(0)));
        if (mReaseonList.size() - 1 == mChooseReason.get(0)) {
            orderCancelData.setcancelContent(mInputEditText.getText().toString());
        }

        orderCancelData.post(new IDataStatusChangedListener<OrderCancelResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderCancelResponse> comNetData,
                                            OrderCancelResponse orderCancelResponse,
                                            int i) {

                if (orderCancelResponse != null && orderCancelResponse.data != null) {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean("needRefresh",true);
                        goBack(bundle);
                }else{
                    ToastForCarpool.show(mActivity,"网络异常，请稍候再试");
                }

            }
        });

    }

    private void requestOrderStatus() {
        showLoadingDialog(true);
        OrderDetailData orderDetailData = new OrderDetailData(mActivity);
        orderDetailData.setOrderId(this.oderId);
        orderDetailData.post(new IDataStatusChangedListener<OrderDetailResponse>() {
            @Override
            public void onDataStatusChanged(ComNetData<OrderDetailResponse> comNetData,
                                            OrderDetailResponse orderDetailResponse,
                                            int i) {
                if (orderDetailResponse != null && orderDetailResponse.data != null) {
                    mOrderStatus = orderDetailResponse.data.orderStatusId;
                    if (mOrderStatus == 2){
                        //等待抢单
                        showWaitReceipt();
                    }
                } else {
                    ToastForCarpool.show(mActivity, "网络异常，请检查网络");
                }
                showLoadingDialog(false);
                Bundle b = new Bundle();
                b.putBoolean("needRefresh",false);
                goBack(b);
            }
        });
    }

    @Override
    public boolean onBackPressed() {
        if (!checkNetworkStatus(false)){
            return super.onBackPressed();
        }
        requestOrderStatus();
        //其他状态均返回到上一页
        return true;

    }

    private void showWaitReceipt() {
        CarPoolReceiptDialog carPoolReceiptDialog = new CarPoolReceiptDialog(mActivity, oderId, 2);
        carPoolReceiptDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_view:
               // if (!checkNetworkStatus(false)){
                  goBack();
              //  }
               // requestOrderStatus();
                //其他状态均返回到上一页
                break;
            case R.id.btn_cancel_order:
                mCancelOrderBtn.setBackgroundResource(R.drawable.press_shurukuang);
                mCancelOrderBtn.setTextColor(Color.WHITE);
                mSaveOrderBtn.setBackgroundResource(R.drawable.select_shurukuang);
                mSaveOrderBtn.setTextColor(APIProxy.res().getResources().getColor(R.color.cancel_button));
                if (mReaseonList.size() - 1 == mChooseReason.get(0)) {
                    if (TextUtils.isEmpty(mInputEditText.getText().toString())) {
                        ToastForCarpool.show(mActivity, "请输入理由");
                        return;
                    }
                }
                cancelOrder();
                break;
            case R.id.btn_save_order:
                mCancelOrderBtn.setBackgroundResource(R.drawable.select_shurukuang);
                mCancelOrderBtn.setTextColor(APIProxy.res().getResources().getColor(R.color.cancel_button));
                mSaveOrderBtn.setBackgroundResource(R.drawable.press_shurukuang);
                mSaveOrderBtn.setTextColor(Color.WHITE);
                goBack();
                break;
        }

    }

    private class ReasonAdapter extends BaseAdapter {
        ViewHolder mViewHolder = null;

        @Override
        public int getCount() {
            return mReaseonList.size();
        }

        @Override
        public Object getItem(int i) {
            return mReaseonList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                mViewHolder = new ViewHolder();
                view = APIProxy.res().inflate(R.layout.item_cancel_order, null);
                view.setTag(mViewHolder);
            }
            mViewHolder = (ViewHolder) view.getTag();
            mViewHolder.reasenTv = (TextView) view.findViewById(R.id.tv_reason);
            mViewHolder.chooseIv = (ImageView) view.findViewById(R.id.iv_choose_cancel_reason);
            mViewHolder.mLineView = view.findViewById(R.id.line_cancel);
            mViewHolder.reasenTv.setText(mReaseonList.get(i));
            mViewHolder.chooseIv.setImageResource(R.drawable.home_weixuanzhong);
            if (i == mReaseonList.size() - 1) {
                mViewHolder.mLineView.setVisibility(View.GONE);
            } else {
                mViewHolder.mLineView.setVisibility(View.VISIBLE);
            }

            for (int k = 0; k < mChooseReason.size(); k++) {
                if (i == mChooseReason.get(k)) {
                    mViewHolder.chooseIv.setImageResource(R.drawable.home_xuanzhong);
                    break;
                }
            }

            return view;
        }
    }

    private class ViewHolder {
        TextView reasenTv = null;
        ImageView chooseIv = null;
        private View mLineView = null;

    }

}